package com.itrip.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.itrip.common.EmptyUtils;
import com.itrip.entity.ItripHotelTempStore;
import com.itrip.dao.ItripHotelTempStoreMapper;
import com.itrip.service.ItripHotelTempStoreService;
import com.itrip.vo.order.PreAddOrderVO;
import com.itrip.vo.order.RoomStoreVO;
import com.itrip.vo.store.StoreVO;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;

@Service
public class ItripHotelTempStoreServiceImpl extends ServiceImpl<ItripHotelTempStoreMapper, ItripHotelTempStore> implements ItripHotelTempStoreService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ItripHotelTempStoreServiceImpl.class);

    @Resource
    private ItripHotelTempStoreMapper itripHotelTempStoreMapper;

    @Override
    public RoomStoreVO queryRoomStore(PreAddOrderVO preAddOrderVO) {
        Map map = new HashMap();
        //入住时间
        map.put("startTime", preAddOrderVO.getCheckInDate());
        //退房时间
        map.put("endTime", preAddOrderVO.getCheckOutDate());
        //房型id
        map.put("roomId", preAddOrderVO.getRoomId());
        //酒店id
        map.put("hotelId", preAddOrderVO.getHotelId());
        //刷新订单
        itripHotelTempStoreMapper.flushStore(map);
        List<RoomStoreVO> roomStoreVO = null;
        do {
            //查询库存
            roomStoreVO = itripHotelTempStoreMapper.queryRoomStore(preAddOrderVO.getRoomId().intValue(), preAddOrderVO.getCheckInDate(), preAddOrderVO.getCheckOutDate());
            if (roomStoreVO == null || roomStoreVO.get(0).getStore() == null) {
                //刷新订单
                itripHotelTempStoreMapper.flushStore(map);
            }
        } while (roomStoreVO == null || roomStoreVO.get(0).getStore() == null);

        return roomStoreVO.get(0);
    }

    @Override
    public Boolean validateRoomStore(Map<String, Object> param) {
        Integer count = (Integer) param.get("count");
        itripHotelTempStoreMapper.flushStore(param);
        SimpleDateFormat sb = new SimpleDateFormat();
        List<RoomStoreVO> storeVOList = itripHotelTempStoreMapper.queryRoomStore(Integer.valueOf((Integer) param.get("roomId")),(Date) param.get("startTime"),(Date) param.get("endTime"));
        if(EmptyUtils.isEmpty(storeVOList)){
            return false;
        }
        for (RoomStoreVO vo : storeVOList) {
            if (vo.getStore() < count) {
                return false;
            }
        }
        return true;
    }
}
